package com.knowledge.serve.service.impl;

import com.knowledge.common.utils.ReflectTools;
import com.knowledge.db.mapper.MemberMapper;
import com.knowledge.model.pojo.Member;
import com.knowledge.model.pojo.WsClientInfo;
import com.knowledge.serve.service.MemberService;
import com.knowledge.serve.service.websocket.ChatServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;
    /**
     * @desc 创建用户信息
     * @param member
     */
    @Override
    public void createUser(Member member) {

        member.setGender((short) 1);
        member.setStatus((short) 1);
        member.setCreateTime(LocalDateTime.now());
        member.setUpdateTime(LocalDateTime.now());
        memberMapper.createMember(member);
    }

    /**
     * @desc 通过用户名获取对象信息
     * @param username
     * @return
     */
    @Override
    public Member getUserByAccount(String username) {
        Member user = memberMapper.getUserByAccount(username);
        return user;
    }

    /**
     * @desc 通过id查询用户是否存在
     * @param id
     * @return
     */
    @Override
    public Member getUserById(Integer id) {
        Member user = memberMapper.getUserById(id);
        return user;
    }

    @Override
    public void updateInfo(Member member) {
        memberMapper.updateInfo(member);
    }

    /**
     * @desc 获取用户列表
     * @return
     */
    @Override
    public ArrayList<Member> getMemberList() {
        ArrayList<Member> members = memberMapper.getMemberList();
        ConcurrentHashMap<String, WsClientInfo> chatInfo = ChatServer.getChatInfo();
        log.info("在线聊天信息:{}",chatInfo);

        //过滤核心字段
        String[] filterFiled = {"password"};
        members.forEach(member->{
            if(chatInfo.containsKey(member.getUsername())){
                //如果当前存在的话，那么就设置在线效果
                member.setOnline((short) 2);
            }
            try {
                ReflectTools.filterEntityField(member, filterFiled);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });
        return members;
    }

}
